package com.heima.user.services.impl;

import com.heima.common.constants.user.UserRelationConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.services.ApUserRelationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;

@Service
@Slf4j
public class ApUserRelationServiceImpl implements ApUserRelationService {
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        Integer loginId = user.getId();//登陆人id
        Integer authorApUserId = dto.getAuthorApUserId();//作者id
        Double score = redisTemplate.opsForZSet().score(UserRelationConstants.FOLLOW_LIST + loginId, String.valueOf(authorApUserId));
        if (score != null && dto.getOperation().intValue() == 0) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, "您已关注，请勿重复关注");
        }
        if (loginId.equals(authorApUserId)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "请勿关注自己");
        }
        redisTemplate.multi();
        try {
            if(dto.getOperation().intValue() == 0){
                // 3. 如果是关注  参数1: key   参数2: 元素   参数3: score
                redisTemplate.opsForZSet().add(UserRelationConstants.FOLLOW_LIST+loginId,String.valueOf(authorApUserId),System.currentTimeMillis());
                redisTemplate.opsForZSet().add(UserRelationConstants.FANS_LIST+authorApUserId,String.valueOf(loginId),System.currentTimeMillis());
            }else {
                // 4. 如果是取关
                redisTemplate.opsForZSet().remove(UserRelationConstants.FOLLOW_LIST+loginId,String.valueOf(authorApUserId));
                redisTemplate.opsForZSet().remove(UserRelationConstants.FANS_LIST+authorApUserId,String.valueOf(loginId));
            }
            redisTemplate.exec(); // 提交事务
            return ResponseResult.okResult();
        } catch (Exception e) {
            e.printStackTrace();
            redisTemplate.discard(); // 回滚事务
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"服务器出现异常，关注或取关失败");
        }
    }
}

